package com.zucc.eye.controller;
//import com.software.system.entity.Comment;
//import com.software.system.repository.CommentRepository;
import com.alibaba.fastjson.JSONObject;
import com.zucc.eye.dto.CommentDto;
import com.zucc.eye.dto.IssueDto;
import com.zucc.eye.entity.Comment;
import com.zucc.eye.entity.Issue;
import com.zucc.eye.repository.CommentRepository;
import com.zucc.eye.repository.IssueRepository;
import com.zucc.eye.util.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.PageRequest;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import javax.print.DocFlavor;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @description comment
 * @author zhengkai.blog.csdn.net
 * @date 2022-02-09
 */
//@RestController
//@RequestMapping("/comment")

@Slf4j
@Api(tags = "comment")
@CrossOrigin
@RestController
@RequestMapping("/comment")
public class CommentController {

    @Autowired
    private CommentRepository commentRepository;

    @Resource
    private IssueRepository issueRepository;

    /**
    * 新增或编辑
    */
    @PostMapping("/save")
    @ApiOperation(value = "save Issue", notes = "save Issue")
    public Object save(Comment comment){
        return commentRepository.save(comment);
    }


    Object getCommentsByApi(String commentsUrl){
        log.info("getCommentsByApi");
        //String url1 = UrlUtil.add(api).add(user).add(repo).get();
        //String url1 = build.getUrl();
        //StrUtil.urlAdd(api,user)
        //DocFlavor.URL.ad
        //"url": "https://api.github.com/repos/moshowgame/SpringBootCodeGenerator/issues/121",
        log.info("commentsUrl {}", commentsUrl);
        String string = OkHttpUtil.get(commentsUrl, null);
        //JSONObject jsonObject = JsonUtil.stringToJson(string);
        log.info("string {}", string);
        //List<Comment> comments = JSONObject.parseArray(string, Comment.class);
        List<CommentDto> commentDtos = JSONObject.parseArray(string, CommentDto.class);
        //这是所有的 info
        //是所有的列表吗
        List<Comment> comments = commentDtos.stream()
                .map(o -> o.toEntity()).collect(Collectors.toList());
        log.info("comments {}", comments);
        List<Comment> comments1 = commentRepository.saveAll(comments);
        log.info("comments1 {}", comments1);
        //return ReturnT.success(comments1);
        return ReturnT.success(commentDtos);
    }

    @PostMapping("/comments")
    @ApiOperation(value = "save Issue", notes = "save Issue")
    //public Object comments(@RequestBody  Comment comment){
    public Object comments(@RequestBody Issue issue){
        //comment.getUrl();
        //需要issue的 url
        //String url = issue.getUrl();
        //String s = StrUtil.urlAdd(url, "issues/690/comments");
        //https://api.github.com/repos/vmg/redcarpet/issues/690/comments
        String commentsUrl = issue.getCommentsUrl();
        log.info("commentsUrl {}",commentsUrl);
        String[] split = commentsUrl.split("/");
        String issId=   split[split.length-2];
        String user=   split[4];
        String repo=   split[5];
        //获得 isssue 是不是
        String api="https://api.github.com/repos";
        //UrlUtil build = UrlUtil.builder.add(api).add(user).add(repo).build();
        //String url1 = UrlUtil.builder.add(api).add(user).add(repo).get();
        String url1 = new UrlUtil(api).add(user).add(repo).add("issues").
                add(issId).get();
        log.info("url1 {}",url1);
        //Issue firstByUrl = issueRepository.findFirstByUrl(url1);
        List<Comment> allByIssueUrl = commentRepository.findAllByIssueUrl(url1);
        //log.info("firstByUrl {}",firstByUrl);
        log.info("allByIssueUrl {}",allByIssueUrl);
        //if(firstByUrl==null){
        if(allByIssueUrl.size()==0){
            //没有 需要调用api
           return getCommentsByApi(commentsUrl);
        }
        //issId
        //int issIdInt = Integer.parseInt(issId);
        //List<Comment> allByIssueId = commentRepository.findAllByIssueId(issIdInt);
        //log.info("allByIssueId {}",allByIssueId);
        //List<CommentDto> collect = allByIssueId.stream().map(o -> {
        List<CommentDto> collect = allByIssueUrl.stream().map(o -> {
            //BeanUtils.copyProperties(o,commentDto);
            return new CommentDto(o);
        }).collect(Collectors.toList());
        log.info("collect {}",collect);
        return ReturnT.success(collect);
        //String url1 = UrlUtil.add(api).add(user).add(repo).get();
        //String url1 = build.getUrl();
        //StrUtil.urlAdd(api,user)
        //DocFlavor.URL.ad
        //"url": "https://api.github.com/repos/moshowgame/SpringBootCodeGenerator/issues/121",
        //log.info("commentsUrl {}", commentsUrl);
        //String string = OkHttpUtil.get(commentsUrl, null);
        ////JSONObject jsonObject = JsonUtil.stringToJson(string);
        //log.info("string {}", string);
        ////List<Comment> comments = JSONObject.parseArray(string, Comment.class);
        //List<CommentDto> commentDtos = JSONObject.parseArray(string, CommentDto.class);
        ////这是所有的 info
        ////是所有的列表吗
        //List<Comment> comments = commentDtos.stream()
        //        .map(o -> o.toEntity()).collect(Collectors.toList());
        //log.info("comments {}", comments);
        //List<Comment> comments1 = commentRepository.saveAll(comments);
        //log.info("comments1 {}", comments1);
        ////return ReturnT.success(comments1);
        //return ReturnT.success(commentDtos);
    }

    /**
    * 删除
    */
    @PostMapping("/delete")
    public Object delete(int id){
        Optional<Comment> comment=commentRepository.findById(id);
        if(comment.isPresent()){
            commentRepository.deleteById(id);
            return ReturnT.success("删除成功");
        }else{
            return ReturnT.error("没有找到该对象");
        }
    }

    /**
    * 查询
    */
    @PostMapping("/find")
    public Object find(int id){
        Optional<Comment> comment=commentRepository.findById(id);
        if(comment.isPresent()){
            return ReturnT.success(comment.get());
        }else{
            return ReturnT.error("没有找到该对象");
        }
    }

    /**
    * 分页查询
    */
    @PostMapping("/list")
    public Object list(Comment comment,
                        @RequestParam(required = false, defaultValue = "0") int pageNumber,
                        @RequestParam(required = false, defaultValue = "10") int pageSize) {

            //创建匹配器，需要查询条件请修改此处代码
            ExampleMatcher matcher = ExampleMatcher.matchingAll();

            //创建实例
            Example<Comment> example = Example.of(comment, matcher);
            //分页构造
            Pageable pageable = PageRequest.of(pageNumber,pageSize);

            return commentRepository.findAll(example, pageable);
    }

}